package com.wolfheader.wolfgame.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wolfheader.wolfgame.dao.admin.GameDao;
import com.wolfheader.wolfgame.dao.admin.GameRecordDao;
import com.wolfheader.wolfgame.entity.GamePlayerEntity;
import com.wolfheader.wolfgame.entity.GameRecordEntity;
import com.wolfheader.wolfgame.entity.admin.GameEntity;
import com.wolfheader.wolfgame.service.GameRecordService;
import com.wolfheader.wolfgame.service.admin.GameService;
import com.wolfheader.wolfgame.util.CheckUtils;

/**
 * ServiceImpl -
 * 
 * @author 8615 Team
 * @version 1.0
 */
@Service("gameRecordServiceImpl")
public class GameRecordServiceImpl implements GameRecordService {

	@Autowired
	GameRecordDao gameRecordDao;

	@Autowired
	GameDao gameDao;
	
	@PersistenceContext
	private EntityManager em;

	@Resource(name = "gameServiceImpl")
	private GameService gameService;
	
	@Override
	public void createNewCord(GamePlayerEntity entity, String gameid) {
		GameRecordEntity record = new GameRecordEntity();
		record.setGameid(gameid);
		record.setGamePlayer(entity);
		gameRecordDao.save(record);
	}

	public void updateRecord(GameRecordEntity record) {
		gameRecordDao.save(record);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GameRecordEntity> findListByGameId(String gameid) {
		String hql = "select r from GameRecordEntity r where r.gameid=:gameid order by r.totalScore desc,r.recordDateTime asc";
		Query query = em.createQuery(hql);
		query.setParameter("gameid", gameid);
		query.setFirstResult(0);
		query.setMaxResults(50);
		return query.getResultList();
	}

	@Override
	public boolean saveScore(String gameid, String openid, Integer score) {
		if (!CheckUtils.checkGameIdIsTrue(gameid)) {
			return false;
		}
		GameEntity game = gameDao.findOne(Long.parseLong(gameid));
		// 游戏不存在
		if (game == null) {
			return false;
		}
		// 不在游戏活动时间
		Boolean flag = (Boolean) gameService.checkGameOutTime(game, "1");
		if(flag == false){
			return false;
		}
		Integer maxScore = game.getMaxScore();
		// 超过最大记录分数
		if (maxScore > 0 && score >= maxScore) {
			return false;
		}
		GameRecordEntity record = gameRecordDao.findPlayerByOpenidAndGameid(openid, gameid);
		if (record == null) {
			return false;
		}
		if (record.getScore() < score) {
			// 重新记录分数
			record.setTotalScore(score + record.getAssScore());
			record.setScore(score);
			record.setRecordDateTime(new Date().getTime());
			gameRecordDao.save(record);
		}
		return true;
		// TODO Auto-generated method stub

	}

}